<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #result {
            width: 400px;
            height: 300px;
            border: solid 1px #ddd;
        }
    </style>
</head>

<body>
    <a href="/">首页</a>
    <a href="/about">关于我们</a>
    <hr>

    <div id="result">

    </div>

    <script>
        //获取 a 元素
        let links = document.querySelectorAll("a");

        //绑定事件
        links.forEach(item => {
            item.addEventListener('click', function (e) {
                //取消默认行为
                e.preventDefault();
                //修改 url
                history.pushState({ msg: '我是保存的数据哦' }, null, this.href);
                //根据 路径的变化, 来改变 result 的内容
                switch (location.pathname) {
                    case '/':
                        result.innerHTML = '首页内容';
                        break;
                    case '/about':
                        result.innerHTML = '关于我们';
                        break;
                    default:
                        result.innerHTML = '默认页面';
                        break;
                }
            });
        });

        //事件 popstate
        window.addEventListener('popstate', function(e){
            console.log(e);
            //
            switch (location.pathname) {
                case '/':
                    result.innerHTML = '首页内容';
                    break;
                case '/about':
                    result.innerHTML = '关于我们';
                    break;
                default:
                    result.innerHTML = '默认页面';
                    break;
            }
        });

    </script>
</body>

</html>